package com.fvision.camera;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fvision.camera.appupgrade.FileDownloadInterface;
import com.fvision.camera.appupgrade.UpgradeManager;
import com.fvision.camera.base.BaseActivity;
import com.fvision.camera.bean.CameraStateBean;
import com.fvision.camera.bean.DevFileName;
import com.fvision.camera.iface.ICameraStateChange;
import com.fvision.camera.manager.CameraStateIml;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.manager.DevFileNameManager;
import com.fvision.camera.presenter.MainPresenter;
import com.fvision.camera.receiver.UsbStatesReceiver;
import com.fvision.camera.service.ForegroundService;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.utils.Const;
import com.fvision.camera.utils.FloatCalculator;
import com.fvision.camera.utils.LogUtils;
import com.fvision.camera.utils.SharedPreferencesUtil;
import com.fvision.camera.utils.ToastUtils;
import com.fvision.camera.view.activity.PermissionsActivity;
import com.fvision.camera.view.activity.PlaybackActivity;
import com.fvision.camera.view.customview.DragView;
import com.fvision.camera.view.customview.FloatWindowDialog;
import com.fvision.camera.view.customview.SVDrawRectangle;
import com.fvision.camera.view.iface.IMainView;
import com.huiying.cameramjpeg.LogListener;
import com.huiying.cameramjpeg.UvcCamera;
import com.serenegiant.usb.IFrameCallback;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;


public class MainActivity extends BaseActivity implements IMainView, View.OnClickListener {
    private GLSurfaceView surfaceview;
    private SVDrawRectangle adas_surfaceview;
    private MainPresenter presenter = new MainPresenter(this, this);
    private AnimationSet scale0to100, scale100to0;
    private Animation r2lanimation, l2ranimation;
    private RelativeLayout layout_no_signal = null;
    private View leftmenu;
    private Button calibration,check_ok,check_cancel;
    private TextView test_version, device_model;
    private ImageView photo_preview = null;
    private boolean is_snapshot_voice;
    private LinearLayout mute_switch, record_switch, snapshot, lock_switch, setting;
    private LinearLayout ll_playback_1, ll_hotspot_1, ll_format_ft, ll_setting_1;
    private ImageView popupWindow, back;
    private RelativeLayout rootview;
    private FloatWindowDialog mFloatWindowDialog;
    private ProgressBar appUpgradeProgress = null;
    private TextView appUpgradeProgressValue = null;
    private TextView sanction_tips = null;
    private List<String> snapshots = new ArrayList<>();
    private boolean onlyOnce = false;

    public static int hasRun = -1;

    public static final int REQUEST_CODE = 0; // 请求码
    public static final int REQUEST_CODE_INSERT_USB = 1;//插入USB时请求的权限
    public static final int REQUEST_CODE_PHOTO = 2;//拍照时请求的权限
    public static final int REQUEST_CODE_APP_UPGRESS = 3;//App升级时请求的权限

    private final int DELAY_HIDE_TIME = 10 * 1000;
    private final int WHAT_RESREFH_VIEW = 0;
    private final int WHAT_UPDATE_NO_SIGNAL = 1;
    private final int WHAT_HIDE_CONTROL_VIEW = 2;
    private final int WHAT_APP_UPGRADE_PROGRESS = 3;
    private final int WHAT_OPEN_FAIL_ERROR = 5;
    private final int WHAT_SHOW_DEVICE_INFO = 10;
    private final int WHAT_RESET_SERVICE = 40;
    private final int WHAT_DRAW = 30;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_RESREFH_VIEW:
                    presenter.showFormatSdDialog();
                    resrefhStateView();
                    break;
                case WHAT_UPDATE_NO_SIGNAL:
                    boolean isShow = (boolean) msg.obj;
                    showNoSignal(isShow);
                    break;
                case WHAT_HIDE_CONTROL_VIEW:
                    showControlView(false);
                    break;
                case WHAT_APP_UPGRADE_PROGRESS:
                    int progress = (Integer) msg.obj;
                    showAppUpgradeProgress(progress);
                    break;
                case WHAT_OPEN_FAIL_ERROR:
                    RelativeLayout prompt = (RelativeLayout) findViewById(R.id.layout_undetected_device);
                    ImageView id_question_mark = (ImageView) findViewById(R.id.id_question_mark);
                    prompt.setVisibility(View.VISIBLE);
                    if (UvcCamera.getInstance().fd_error == null) {
                        return;
                    }

                    if (UvcCamera.getInstance().fd_error.equals("Success") &&
                            UvcCamera.getInstance().fd_error.equals("Success")) {
                        id_question_mark.setBackgroundResource(R.mipmap.usb2);
                    } else if (UvcCamera.getInstance().fd_error.equals("not found file")) {
                        id_question_mark.setBackgroundResource(R.mipmap.usb1);
                    }
                    break;
//                case WHAT_SHOW_DEVICE_INFO:
//                    printTestPrompt();
//                    break;
                case WHAT_DRAW:
                    draw();
                    break;
                case WHAT_RESET_SERVICE:
                    if (layout_no_signal != null && layout_no_signal.getVisibility() == View.GONE) {
                        return;
                    }
                    if (UvcCamera.getInstance().fd_error != null &&
                            UvcCamera.getInstance().fd_error.equals("Success")) {
                        stopService(new Intent(MainActivity.this, ForegroundService.class));
                        startService(new Intent(MainActivity.this, ForegroundService.class));
                    }
                    break;
            }
        }
    };

    private void draw() {
        if (surfaceview == null) {
            mHandler.sendEmptyMessageDelayed(WHAT_DRAW, 40);
            return;
        }
        surfaceview.requestRender();
        mHandler.sendEmptyMessageDelayed(WHAT_DRAW, 40);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d("mainActivity onCreate()");
        hasRun = 1;
        UpgradeManager.init(MainActivity.this, "DriveRecorder.apk");
        resetPreview(rootview);
        getLastPath();
//        UvcCamera.getInstance().setOnLog(mLogListener);
        presenter.checkPermission(MainActivity.REQUEST_CODE);
//        if(!CameraStateUtil.isServiceRunning("com.fvision.camera.service.ForegroundService",this)){
//
//            startService(new Intent(this, ForegroundService.class));
//        }
        if (Confecting.APP_UPGRADE_CHANNEL.equals(".px3")) {
            presenter.startCamera("/mnt/media_rw");
        } else {
            presenter.startCamera(null);
        }
//        presenter.initAudio();
        showCamera();
        showControlView(false);
        resrefhStateView();
        //  isPendingIntent();
        startService(new Intent(this, ForegroundService.class));
        sendBroadcast(new Intent(Const.BROAD_CAST_HIDE_FLOATWINDOW));
//        new Thread(openFailCheckThread).start();
        new Thread(openFailCheckThread).start();
        mHandler.sendEmptyMessageDelayed(WHAT_RESET_SERVICE, 1000);
//        mHandler.sendEmptyMessageDelayed(WHAT_SHOW_DEVICE_INFO,3000);
        mHandler.sendEmptyMessage(WHAT_DRAW);
        sanction();
    }


    private void ajust(){
        adas_surfaceview.setIsDraw(false);
        adas_surfaceview.drawCheckLine();
    }

    public LogListener mLogListener = new LogListener() {
        @Override
        public void writeFile(String msg) {
            LogUtils.write("zoulequan", msg);
        }
    };


    private void getLastPath() {
        if (Confecting.APP_UPGRADE_CHANNEL.equals(".px3")) {
            UvcCamera.getInstance().setSerachDevpath("/mnt/media_rw");
        } else {
            String devpath = (String) SharedPreferencesUtil.getData(this, SharedPreferencesUtil.USB_PATH, "");
            if (devpath != null) {
                UvcCamera.getInstance().setDevpath(devpath);
                String searchDir = devpath.substring(0, devpath.indexOf('/', 1) + 1);
                UvcCamera.getInstance().setSerachDevpath(searchDir);
                LogUtils.d("SharedPreferencesUtil.getUsbPath(this) = " + devpath + " setSerachDevpath " + searchDir);
            }
        }
    }

    Runnable openFailCheckThread = new Runnable() {
        @Override
        public void run() {
            if (layout_no_signal != null && layout_no_signal.getVisibility() == View.GONE) {
                return;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(!CameraStateUtil.isForeground(getApplicationContext(),"MainActivity")){
                return;
            }
            printTestPrompt();
        }
    };

    public void printTestPrompt() {
        mHandler.sendEmptyMessage(WHAT_OPEN_FAIL_ERROR);
    }

    public void showAppUpgradeProgress(float progress) {
        appUpgradeProgress.setVisibility(View.VISIBLE);
        appUpgradeProgressValue.setVisibility(View.VISIBLE);
        appUpgradeProgress.setProgress((int) progress);
        appUpgradeProgressValue.setText("" + (int) progress + "%");
    }

    private void sanction() {
        LogUtils.d(" sanction() " + SharedPreferencesUtil.isSanction(this));
        sanction_tips.setVisibility(SharedPreferencesUtil.isSanction(this) ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        adas_surfaceview.setZOrderOnTop(true);
        adas_surfaceview.setZOrderMediaOverlay(true);
        adas_surfaceview.getHolder().setFormat(PixelFormat.TRANSPARENT);
        LogUtils.d("mainActivity onResume()");
    }

    private void showCamera() {
        surfaceview.setEGLContextClientVersion(2);//// 创建一个OpenGL ES 2.0 context
        surfaceview.setRenderer(new GLSurfaceView.Renderer() {
            @Override
            public void onSurfaceCreated(GL10 gl, EGLConfig config) {
                UvcCamera.getInstance().initGles(1280, 720);
            }

            @Override
            public void onSurfaceChanged(GL10 gl, int width, int height) {
                UvcCamera.getInstance().changeESLayout(width, height);
            }

            @Override
            public void onDrawFrame(GL10 gl) {
                if (UvcCamera.getInstance().drawESFrame() == 0) {
                    if (!onlyOnce) {//记录上一次成功预览的固件版本
                        String deviceVersion = CmdManager.getInstance().getCurrentState().getPasswd();
                        if (TextUtils.isEmpty(deviceVersion)) {
                            return;
                        }
                        SharedPreferencesUtil.setLastDevVersion(getApplicationContext(),deviceVersion);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                presenter.getSanction();
                            }
                        }).start();
                        onlyOnce = true;
                    }
                    sendNoSignalMessage(false);
                }
            }
        });
        surfaceview.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);// openGL
    }

    private void hideLeftMenu() {
        leftmenu.setVisibility(View.GONE);
    }

    private void showLeftMenu() {
        leftmenu.setVisibility(View.VISIBLE);
    }

    private void resrefhStateView() {
        if (isFinishing()) {
            return;
        }
        CameraStateBean state = CmdManager.getInstance().getCurrentState();
        if (state.getStateFrame() == null) {
            return;
        }
        if(state.getAdasState() == 1){
            showToast("车道偏离");
            presenter.playAdasSound();
            if(adas_surfaceview!=null){
                adas_surfaceview.setWarning(true);
            }
           // AdasSoundManager.getInstance().playSound(R.raw.adas_ldw2);
        }
       // state.print();
        findViewById(R.id.tf_state).setSelected(state.isCam_sd_state());
        findViewById(R.id.lock_state).setVisibility(state.isCam_lock_state() ? View.VISIBLE : View.GONE);
        findViewById(R.id.camera_mic_state).setSelected(!state.isCam_mute_state());
        findViewById(R.id.iv_camera_audio).setSelected(!state.isCam_sd_state());
        findViewById(R.id.iv_camera_lock).setSelected(state.isCam_lock_state());
        findViewById(R.id.iv_record).setSelected(state.isCam_sd_state());
        findViewById(R.id.camera_recording_state).setVisibility(state.isCam_rec_state() ? View.VISIBLE : View.GONE);
        changeEnable();
        sanction();
    }

    /**
     * 各种开关按钮始能控制
     */
    private void changeEnable() {
        boolean isEnable = CmdManager.getInstance().getCurrentState().isCam_sd_state();
        findViewById(R.id.ll_camera_audio).setEnabled(isEnable);
        findViewById(R.id.iv_camera_audio).setEnabled(isEnable);

        findViewById(R.id.ll_camera_lock).setEnabled(isEnable);
        findViewById(R.id.iv_camera_lock).setEnabled(isEnable);

        findViewById(R.id.ll_record).setEnabled(isEnable);
        findViewById(R.id.iv_record).setEnabled(isEnable);

        findViewById(R.id.ll_snapshot).setEnabled(isEnable);
        findViewById(R.id.iv_snapshot).setEnabled(isEnable);
    }

    /**
     * 无信号时的遮挡界面显示开关
     *
     * @param isShow
     */
    private void showNoSignal(boolean isShow) {
        layout_no_signal.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 无信号时的遮挡界面显示开关
     *
     * @param isShow
     */
    private void sendNoSignalMessage(boolean isShow) {
        Message msg = new Message();
        msg.what = WHAT_UPDATE_NO_SIGNAL;
        msg.obj = isShow;
        mHandler.sendMessage(msg);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {

    }

    @Override
    protected void initView() {
        rootview = (RelativeLayout) findViewById(R.id.rootview);
        surfaceview = (GLSurfaceView) findViewById(R.id.glsurfaceview);
        adas_surfaceview = (SVDrawRectangle)findViewById(R.id.adas_surfaceview);
        layout_no_signal = (RelativeLayout) findViewById(R.id.layout_no_signal);
        leftmenu = findViewById(R.id.left_menu);
        //mute_switch,record_switch,photo_preview,lock_switch,setting;
        mute_switch = (LinearLayout) findViewById(R.id.ll_camera_audio);
        record_switch = (LinearLayout) findViewById(R.id.ll_record);
        snapshot = (LinearLayout) findViewById(R.id.ll_snapshot);
        lock_switch = (LinearLayout) findViewById(R.id.ll_camera_lock);
        setting = (LinearLayout) findViewById(R.id.ll_setting);
        photo_preview = (ImageView) findViewById(R.id.photo_preview);
        popupWindow = (ImageView) findViewById(R.id.home);
        popupWindow.setVisibility(Confecting.IS_HIDE_FLOATWINDOWS ? View.GONE : View.VISIBLE);

        back = (ImageView) findViewById(R.id.iv_back);
        ll_playback_1 = (LinearLayout) findViewById(R.id.ll_playback_1);
        ll_hotspot_1 = (LinearLayout) findViewById(R.id.ll_hotspot_1);
        ll_format_ft = (LinearLayout) findViewById(R.id.ll_format_ft);
        ll_setting_1 = (LinearLayout) findViewById(R.id.ll_setting_1);
        test_version = (TextView) findViewById(R.id.test_version);
        test_version.setVisibility(App.isTestVersion ? View.VISIBLE : View.GONE);
        device_model = (TextView) findViewById(R.id.device_model);
        device_model.setText(Build.MODEL);
        appUpgradeProgress = (ProgressBar) findViewById(R.id.app_upgrade_progress);
        appUpgradeProgressValue = (TextView) findViewById(R.id.app_upgrade_progress_value);
        sanction_tips = (TextView)findViewById(R.id.sanction_tips);
        calibration = (Button)findViewById(R.id.check);
        check_ok = (Button)findViewById(R.id.check_ok);
        check_cancel = (Button)findViewById(R.id.check_cancel);
        View camera_recording_state = findViewById(R.id.camera_recording_state);
        //视频录制状态动画，红点闪烁
        AnimationDrawable animationDrawable = (AnimationDrawable) camera_recording_state.getBackground();
        animationDrawable.start();
//        AnimationDrawable animationDrawable1 = (AnimationDrawable) findViewById(R.id.lane).getBackground();
//        animationDrawable1.start();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        surfaceview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                surfaceview_onClick();
            }
        });
        mute_switch.setOnClickListener(this);
        record_switch.setOnClickListener(this);
        lock_switch.setOnClickListener(this);
        setting.setOnClickListener(this);
        photo_preview.setOnClickListener(this);
        snapshot.setOnClickListener(this);
        popupWindow.setOnClickListener(this);
        back.setOnClickListener(this);
        ll_playback_1.setOnClickListener(this);
        ll_hotspot_1.setOnClickListener(this);
        ll_format_ft.setOnClickListener(this);
        ll_setting_1.setOnClickListener(this);

        UpgradeManager.getInstance().setOnProgressChangeListener(new FileDownloadInterface() {
            @Override
            public void progress(float progress) {
                Message msg = new Message();
                msg.what = WHAT_APP_UPGRADE_PROGRESS;
                msg.obj = (int) progress;
                mHandler.sendMessage(msg);
            }

            @Override
            public void complete(String filepath) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast(getString(R.string.download_complete));
                        appUpgradeProgress.setVisibility(View.GONE);
                        appUpgradeProgressValue.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void fail(int code, String error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismisLoadingDialog();
                        showToast(getString(R.string.download_fail));
                        appUpgradeProgress.setVisibility(View.GONE);
                        appUpgradeProgressValue.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void update(final int version_code, final String path, final String app_desc, final String version) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismisLoadingDialog();
                        String upgradePint = null;
                        if (Confecting.APP_UPGRADE_CHANNEL.equals(".px3")) {
                            upgradePint = "Add ADAS";
                        } else {
                            upgradePint = getString(R.string.upgrade_pint);
                        }
                        UpgradeManager.getInstance().update(version_code, path, upgradePint, version);
                    }
                });
            }
        });

        calibration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                UvcCamera.getInstance().setLanePos(x1,y1);
//                byte[] params = new byte[8];
//                UvcCamera.getInstance().getLanePos(params);
//                int x = (int)(FloatCalculator.multiply(byte2Short(params,0,4),FloatCalculator.divide(adas_surfaceview.getmWidth(),1280f))) ;
//                int y = (int)(FloatCalculator.multiply(byte2Short(params,4,4),FloatCalculator.divide(adas_surfaceview.getmWidth(),720f))) ;

//                LogUtils.d("adas draw 从记录仪取原始的1x "+byte2Short(params,0,4)+" y "+byte2Short(params,4,4) + " "+adas_surfaceview.getmWidth());
                adas_surfaceview.setVisibility(View.VISIBLE);
                adas_surfaceview.setsConfigX(getX());
                adas_surfaceview.setsConfigY(getY());
                LogUtils.d("adas draw 从记录仪取转换后的x "+getX()+" y "+getY());
                ajust();
            }
        });

        adas_surfaceview.setListener(new SVDrawRectangle.IAdasConfigListener() {
            @Override
            public void setAdasConfigXY(float x, float y) {
 //               showToast("设置 存在记录仪里的 x "+(int)x + " y "+(int)y);
                SharedPreferencesUtil.setCalibrationX(getApplicationContext(),(int)x);
                SharedPreferencesUtil.setCalibrationY(getApplicationContext(),(int)y);
                UvcCamera.getInstance().setLanePos((int)x,(int)y);
//                lane.layout((int)x,(int)y);
            }

            @Override
            public void surfaceChanged() {
                adas_surfaceview.setsConfigX(getX());
                adas_surfaceview.setsConfigY(getY());
                adas_surfaceview.setCheckpointXY1();
//                UvcCamera.getInstance().setLanePos(getX(),getY());
            }
        });

        check_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //  adas_surfaceview.setVisibility(View.GONE);
                adas_surfaceview.setCheckpointXY1();
                adas_surfaceview.setIsDraw(true);
            }
        });

        check_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adas_surfaceview.setVisibility(View.GONE);
            }
        });

        adas_surfaceview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    surfaceview_onClick();
                }
                return false;
            }
        });
    }

    private int getX(){
        int share_x = SharedPreferencesUtil.getCalibrationX(getApplicationContext());
        if(share_x == 0){
            return adas_surfaceview.getmWidth()/2;
        }
        return (int)(FloatCalculator.multiply(share_x,FloatCalculator.divide(adas_surfaceview.getmWidth(),1280f))) ;
    }

    private int getY(){
        int share_y = SharedPreferencesUtil.getCalibrationY(getApplicationContext());
        if(share_y == 0){
            return adas_surfaceview.getmHeight()/2;
        }
        return (int)(FloatCalculator.multiply(share_y,FloatCalculator.divide(adas_surfaceview.getmHeight(),720f))) ;
    }

    private short byte2Short(byte[] stateFrame, int startPos, int length) {
        byte[] newByte = new byte[length < 2 ? 2 : length];
        System.arraycopy(stateFrame, startPos, newByte, 0, length);
//        LogUtils.d(" newByteShort "+CameraStateUtil.bytesToHexString(newByte));
        return bytesToShort(newByte, 0);
    }

    private short bytesToShort(byte[] src, int offset) {
        short value;
        value = (short) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
        );
        return value;
    }

    /**
     * 视频画面单击事件
     */
    private void surfaceview_onClick() {
        View left_bar = findViewById(R.id.left_bar);
        View setting_layout = findViewById(R.id.left_menu);
        boolean isShow = left_bar.getVisibility() == View.VISIBLE;
        showControlView(!isShow);
        if (!isShow) {
            timerHideControlView();
        }
        setting_layout.setVisibility(View.GONE);
    }

    private void showControlView(boolean isShow) {
        View left_bar = findViewById(R.id.left_bar);
        View right_bar = findViewById(R.id.right_bar);
        View photo_review = findViewById(R.id.photo_preview);

        if (isShow) {
            showScale0to100(left_bar);
            showScale0to100(right_bar);
//            showRight2LeftView(photo_review);
        } else if (left_bar.getVisibility() == View.VISIBLE) {
            hideScale100to0(left_bar);
            hideScale100to0(right_bar);
//            hideLeft2RightView(photo_review);
        }

    }

    /**
     * 定时隐藏控件
     */
    private void timerHideControlView() {
        mHandler.removeMessages(WHAT_HIDE_CONTROL_VIEW);
        mHandler.sendEmptyMessageDelayed(WHAT_HIDE_CONTROL_VIEW, DELAY_HIDE_TIME);
    }

    private void showScale0to100(View v) {
        if (scale0to100 == null) {
            scale0to100 = (AnimationSet) AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale_0_to_100);
        }
        v.startAnimation(scale0to100);
        v.setVisibility(View.VISIBLE);
    }

    private void hideScale100to0(View v) {
        if (scale100to0 == null) {
            scale100to0 = (AnimationSet) AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale_100_to_0);
        }
        v.startAnimation(scale100to0);
        v.setVisibility(View.GONE);
    }

    private void showRight2LeftView(View v) {
        if (r2lanimation == null)
            r2lanimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
        v.startAnimation(r2lanimation);
        v.setVisibility(View.VISIBLE);
    }

    private void hideLeft2RightView(View v) {
        if (l2ranimation == null)
            l2ranimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate_left_to_right);
        v.startAnimation(l2ranimation);
        v.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoadingDialog();
            }
        });
    }

    @Override
    public void closeLoading() {
        dismisLoadingDialog();
    }

    @Override
    public void showToast(String msg) {
        ToastUtils.showToast(getApplicationContext(), msg);
    }


    @Override
    public void resrefhView() {
        mHandler.sendEmptyMessage(WHAT_RESREFH_VIEW);
    }

    @Override
    public void usbStateChange(String path, int state) {
//        sendNoSignalMessage(state == UsbStatesReceiver.USB_STATE_OFF);
        if (state == UsbStatesReceiver.USB_STATE_ON) {
            if (Confecting.APP_UPGRADE_CHANNEL.equals(".px3")) {
                presenter.insertUsb(path.replace("/storage", "/mnt/media_rw"));
            } else {
                presenter.insertUsb(path);
            }
        } else {
//            CameraStateBean state1 = CmdManager.getInstance().getCurrentState();
//            if(state1.getStateFrame()!=null && state1.getStateFrame()[0] == 0x55 &&
//                    state1.getStateFrame()[1] == 0x55 &&
//                    state1.getStateFrame()[2] == 0x55){
//                    presenter.pullUsb();
//            }
//            presenter.pullUsb();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_camera_audio://静音开关
                switchMute();
                break;
            case R.id.ll_record://录像开关
                switchRecord();
                break;
            case R.id.ll_camera_lock://录像锁开关
            //    test();
                switchLock();
                break;
            case R.id.ll_snapshot://拍照
                takePicture_screenshot();
                break;
            case R.id.ll_setting://设置
                goSetting();
                break;
            case R.id.photo_preview://图片预览
                // photoPreview();
                break;
            case R.id.ll_playback_1://回放
                goPlayBackActivity();
                break;
            case R.id.home://小窗口
                showPopupWindow();
                break;
            case R.id.iv_back://返回
                presenter.pullUsb();
                break;
            case R.id.ll_setting_1:
                presenter.showSettingDialog();
                break;
            case R.id.ll_hotspot_1://版本号
                presenter.showAppVersion();
                break;
            case R.id.ll_format_ft://格式化tf
                formatTf();
                break;
        }
    }

    private void test(){
        String folder1="Android";//一级目录
        String folder2="data";//二级目录
        String folder3="com.fvision.camera";//二级目录

        String devpath = UvcCamera.getInstance().getDevpath();
        LogUtils.write("zoulequan","devpath "+devpath);
        File uPath = new File(devpath).getParentFile();
        if(uPath!=null){
            File dirFirstFile=new File(uPath,folder1);//新建一级主目录

            if(!dirFirstFile.exists()){//判断文件夹目录是否存在

                dirFirstFile.mkdir();//如果不存在则创建

            }

            File dirSecondFile=new File(dirFirstFile,folder2);//新建二级主目录

            if(!dirSecondFile.exists()){//判断文件夹目录是否存在

                dirSecondFile.mkdir();//如果不存在则创建

            }
            File dirThreeFile=new File(dirSecondFile,folder3);//新建二级主目录

            if(!dirThreeFile.exists()){//判断文件夹目录是否存在
                dirThreeFile.mkdir();//如果不存在则创建
            }

            File cmd=new File(dirThreeFile,"HWC");//新建二级主目录
            if(!cmd.exists()){//判断文件夹目录是否存在
                try {
                    cmd.createNewFile();//如果不存在则创建
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            showToast("U盘目录未找到 "+uPath);
        }
    }

    /**
     * 同步时间
     */
    private void syncTime() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().syncTime();
            }
        }).start();
    }

    private void sendCmd(Runnable runnable, final String toastContent) {
        if (!CmdManager.getInstance().getCurrentState().isCam_sd_state()) {
            ToastUtils.showLongToast(this, R.string.has_no_tfcard);
            return;
        }
        showLoadingDialog();
        timeOutCloseLoadingDialog(1000);
        new Thread(runnable).start();

        CameraStateIml.getInstance().setOnCameraStateOnlyOnceListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismisLoadingDialog();
                        if (toastContent != null) {
                            ToastUtils.showToast(getApplicationContext(), toastContent);
                        }
                    }
                });
            }
        });
    }

    private void showPopupWindow() {

        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                if(mFloatWindowDialog == null){
                    mFloatWindowDialog = new FloatWindowDialog(MainActivity.this);
                }
                mFloatWindowDialog.show();
                mFloatWindowDialog.setOnFloatWindonsClickLinteners(new FloatWindowDialog.OnFloatWindonsClickLinteners() {
                    @Override
                    public void onOk(View view) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }

                    @Override
                    public void onCancel(View view) {

                    }
                });
            } else {
                //执行6.0以上绘制代码
                finish();
                sendBroadcast(new Intent(Const.BROAD_CAST_SHOW_FLOATWINDOW));
            }
        }else {
            //执行6.0以上绘制代码
            finish();
            sendBroadcast(new Intent(Const.BROAD_CAST_SHOW_FLOATWINDOW));
        }


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.d("onNewIntent close service");
        sendBroadcast(new Intent(Const.BROAD_CAST_HIDE_FLOATWINDOW));
    }

    public void photoPreview() {
        gotoSnapshotPreview();
    }

    public void goSetting() {
        showLeftMenu();

        showControlView(false);
    }

    /**
     * 格式化tf
     */
    private void formatTf() {
        sendCmd(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().formatTf();
            }
        }, getString(R.string.format_tf_sucess));
    }

    /**
     * 录像开关
     */
    private void switchRecord() {
        sendCmd(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().recToggle();
            }
        }, null);
    }

    /**
     * 录制声音开关
     */
    private void switchMute() {
        sendCmd(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().recSoundToggle();
            }
        }, null);
    }

    /**
     * 录制锁开关
     */
    private void switchLock() {
        sendCmd(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().lockToggle();
            }
        }, null);
    }

    /**
     * 拍照,小系统方式
     */
    private void takePicture() {
        if (!CmdManager.getInstance().getCurrentState().isCam_sd_state()) {
            ToastUtils.showLongToast(this, R.string.has_no_tfcard);
            return;
        }
        showLoadingDialog();
        timeOutCloseLoadingDialog(1000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().takePictures();
            }
        }).start();
        CameraStateIml.getInstance().setOnCameraStateOnlyOnceListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismisLoadingDialog();
                        ToastUtils.showToast(getApplicationContext(), R.string.take_snapshot_sucess);
                    }
                });
            }
        });
    }

    /**
     * 拍照,截屏方式
     */
    private void takePicture_screenshot() {
        if (!CmdManager.getInstance().getCurrentState().isCam_sd_state()) {//检测sd卡
            ToastUtils.showToast(this, R.string.has_no_tfcard);
            return;
        }
        showLoadingDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss-SSS");
                String name = format.format(new Date()) + ".jpg";
                final String path = Const.JPG_PATH + name;
                // final String path = getFilesDir()+"/"+ name;
                final boolean sucess = UvcCamera.getInstance().takeSnapshot(path);//这里存的照片

                presenter.playVoice();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (sucess) {
                            ToastUtils.showLongToast(getApplicationContext(), R.string.take_snapshot_sucess);
                            snapshots.add(0, path);
                            showSnapshot();
                        } else {
                            presenter.checkPermission(REQUEST_CODE_PHOTO);//截屏方式才需要权限，小系统拍照不需要
//                            if (presenter.isCreateFilePermission() && presenter.isWritePermission()) {
//                                ToastUtils.showLongToast(getApplicationContext(),R.string.take_snapshot_fail);
//                            }
                        }
                        dismisLoadingDialog();
                    }
                });
            }
        }).start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            ToastUtils.showToast(this, "请求被拒绝");
            return;
        }
        ToastUtils.showToast(this, "请求被授予 " + requestCode);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE) {
            presenter.startCamera(null);
        } else if (requestCode == REQUEST_CODE_INSERT_USB) {
            String temPath = (String) SharedPreferencesUtil.getData(this, SharedPreferencesUtil.TEMPORARY_USB_PATH, "");
            if (!temPath.equals("")) {
                if (CameraStateUtil.isMyUsb(temPath)) {
                    String devpath = temPath + "/" + DevFileNameManager.getInstance().getCurrentDev().getPreView();
                    SharedPreferencesUtil.saveData(this, SharedPreferencesUtil.USB_PATH, devpath);
                    UvcCamera.getInstance().setDevpath(devpath);
                    presenter.insertUsb(devpath);
                }
            }
            ToastUtils.showToast(this, "请求被授予");
        }
    }

    /**
     * 跳转回放页面
     */
    private void goPlayBackActivity() {
        if (!CmdManager.getInstance().getCurrentState().isCam_sd_state()) {//检测sd卡
            ToastUtils.showLongToast(this, R.string.has_no_tfcard);
            return;
        }
        if (!CmdManager.getInstance().getCurrentState().isCam_rec_state() && CmdManager.getInstance().getCurrentState().isCam_mode_state()) {
            hideLeftMenu();
            UvcCamera.getInstance().setMainRuning(false);
            Intent intent = new Intent(MainActivity.this, PlaybackActivity.class);
            startActivity(intent);
            return;
        }
        showLoadingDialog();
        timeOutCloseLoadingDialog(2000);
        CameraStateIml.getInstance().setOnCameraStateCustomListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                CameraStateBean state = CmdManager.getInstance().getCurrentState();
                if (state.isCam_mode_state()
                        && !state.isCam_rec_state()
                        && state.getFile_index() > -1
                        && state.isCam_plist_state()) {
                    CameraStateIml.getInstance().setOnCameraStateCustomListner(null);
                    LogUtils.d("满足进入回放模式条件");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideLeftMenu();
                            dismisLoadingDialog();
                            UvcCamera.getInstance().setMainRuning(false);
                            Intent intent = new Intent(MainActivity.this, PlaybackActivity.class);
                            startActivity(intent);
                        }
                    });
                }
            }
        });

        if (CmdManager.getInstance().getCurrentState().isCam_rec_state()) {//判断是否在录像
            CmdManager.getInstance().recToggle();
        }

        if (!CmdManager.getInstance().getCurrentState().isCam_mode_state()) {//如果不是回放模式
            CmdManager.getInstance().modelToggle();
        }
    }

    private void showSnapshot() {
        if (snapshots.size() > 0) {
            photo_preview.setImageURI(Uri.fromFile(new File(snapshots.get(0))));
            photo_preview.setVisibility(View.GONE);
        } else {
            photo_preview.setVisibility(View.GONE);
        }
    }

    private void gotoSnapshotPreview() {
//        Intent preview = new Intent(mContext, ImagePreviewActivity.class);
//        preview.putStringArrayListExtra(ImagePreviewActivity.KEY_FILEBEANS, (ArrayList<String>) snapshots);
//        startActivityForResult(preview, 0x10);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            presenter.pullUsb();
        }
        return super.onKeyDown(keyCode, event);
    }
}
